package java8.atguigu.teacher.optional;

import java8.atguigu.lu.l01.Employee;
import org.junit.Test;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @program lambda
 * @description:
 * @author: zhanglu
 * @create: 2019-06-02 13:00:00
 */
public class TestOptional01 {

    /*
        Optional 容器类额度常用方法：
        Option.of(T t) ：创建一个Optional 实例
        Optional.empty() ：创建一个空的Optional 实例
        Optional.ofNullable(T t)： 若t不为null，创建Optional实例，否则创建空实例
        isPresent() ：判断是否包含值
        orElse(T t)： 如果调用对象包含值，返回该值，否则返回t
        orElseGet(Supplier s) ： 如果调用对象包含值，返回该值，返回返回s获取的值
        map(Function F)：如果有值对其处理，并返回处理后的Optional，否则返回Optional.empty()
        flatMap(Function mapper)：与map类似，要求返回值必须是Optional
     */
    @Test
    public void test01(){
        Optional<Employee> op = Optional.of(new Employee());
        Employee employee = op.get();
        System.out.println(employee);

        Optional<Employee> op2 = Optional.empty();
        if(op2.isPresent()){
            System.out.println(op2.get());
        }

        Optional<Employee> op3 = Optional.ofNullable(null);
        if(op3.isPresent()){
            System.out.println(op3.get());
        }

        Employee employee1 = op3.orElse(new Employee("zhangsan"));
        System.out.println(employee1);

        Employee employee2 = op3.orElseGet(() -> new Employee("lisi"));
        System.out.println(employee2);

    }

    @Test
    public void test02(){
        Optional<Employee> op = Optional.ofNullable(new Employee("zhangsan"));
        Optional<String> op2 = op.map(e -> e.getName());
        System.out.println(op2.get());

        Optional<String> op3 = op.flatMap(e -> Optional.of(e.getName()));
        System.out.println(op3.get());
    }

    /* ****************实例**************** */

    @Test
    public void test03(){
        Optional<Godness> godness = Optional.ofNullable(new Godness("ss"));
        Optional<Man> man = Optional.ofNullable(new Man(godness));
        System.out.println(getGodnessName(man));
    }

    //获取一个男人心中女神的名字
    public String getGodnessName(Optional<Man> man){
        return man.orElse(new Man())
                .getGodness()
                .orElse(new Godness("苍老师"))
                .getName();
    }

    @Test
    public void test04(){
        String bh = "48e9715c32434e0f9b4695af09f2db00";
        System.out.println(bh.length());
        AtomicReference<StringBuffer> where = new AtomicReference<>(new StringBuffer());
        String res = where.get().toString();
        System.out.println(res);
    }

}
